//
//  WJEssAndNewUpTableVC.m
//  WJBSApp
//
//  Created by dllo on 16/7/18.
//  Copyright © 2016年 王景伟. All rights reserved.
//
// http://s.budejie.com/topic/list/jingxuan/1/budejie-android-6.4.3/0-20.json?
// http://s.budejie.com/topic/list/jingxuan/1/bs0315-iphone-4.2/0-20.json

#import "WJEssAndNewUpTableVC.h"
#import "WJEssAndNewModel.h"
#import "WJEssAndNewButton.h"
#import "WJEssAndNewBaseCell.h"
#import "WJ_TJDY_VC.h"
#import "WJ_Follow_VC.h"
#import "WJEssAndNewPLVC.h"
#import "WJLastViewController.h"
#import "SVProgressHUD.h"
#import "XWPressView.h"

@interface WJEssAndNewUpTableVC ()
// 保存数据
@property (nonatomic,retain) NSMutableArray *array;

@property (nonatomic,assign) BOOL isClick;

@property (nonatomic,strong) NSMutableArray *clickUpButton;

@property (nonatomic,strong) NSMutableArray *clickBelowButton;

@property (nonatomic,assign) BOOL isHas;

@property (nonatomic,assign) BOOL isBelowHas;
//当加载下一页数据是需要这个参数
@property (nonatomic,copy) NSNumber *np;
//上一次请求
@property (nonatomic,strong) NSDictionary *params;
//上次选中的索引(或者控制器)
@property (nonatomic,assign) NSInteger lastSelectedIndex;

@property (nonatomic,assign) NSInteger presentTag;
// 炫酷小菊花
@property (nonatomic,strong) XWPressView *progress;

@end

@implementation WJEssAndNewUpTableVC

static NSString *const UPCell = @"TBCell";

-(void)dealloc
{
    [_url release];
    [_array release];
    [_np release];
    [_clickBelowButton release];
    [_clickUpButton release];
    [_params release];
    [_progress release];
    self.tableView.delegate = nil;
    self.tableView.dataSource = nil;
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [super dealloc];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.array = [NSMutableArray array];
    
    self.clickUpButton = [NSMutableArray array];
    
    self.clickBelowButton = [NSMutableArray array];
    
    [self createView];
    
    //添加刷新控件
    [self setupRefresh];

 }

- (void)createView
{
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.showsVerticalScrollIndicator = NO;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.tableView registerClass:[WJEssAndNewBaseCell class] forCellReuseIdentifier:UPCell];
    
    self.progress = [[XWPressView alloc]init];
    _progress.center = CGPointMake(WIDTH /2, HEIGHT / 2 - 64 - 49 );
    [self.view addSubview:self.progress];
    [_progress release];

    
    // 夜间模式
    if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"Mode"] isEqualToString:@"night"]) {
        self.view.backgroundColor = FIRBLACKCOLOR;
    }else{
        self.view.backgroundColor =  [UIColor whiteColor];
    }
    // 创建观察者
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeColor:) name:@"changeColor" object:nil];
    
    
    // 解决重用问题
     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(clickVideo:) name:@"点击了视屏" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(clickAideo:) name:@"点击了音频" object:nil];
}


- (void)changeColor:(NSNotification *)cation
{
    if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"Mode"] isEqualToString:@"night"]) {
        self.view.backgroundColor = FIRBLACKCOLOR;
    }else{
        self.view.backgroundColor = [UIColor whiteColor];
    }
}

- (void)clickVideo:(NSNotification *)nsnotification
{
    NSString *str = nsnotification.object;
    self.presentTag = str.integerValue;
}

- (void)clickAideo:(NSNotification *)nsnotification
{
    NSString *str = nsnotification.object;
    self.presentTag = str.integerValue;
}


//添加刷新控件
- (void)setupRefresh
{
    //下拉刷新
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    
    //根据下拉的距离提示符自动改变透明度
    self.tableView.mj_header.automaticallyChangeAlpha = YES;
    
    //当已进入页面时自动下拉刷新
    [self.tableView.mj_header beginRefreshing];
    
    //上拉加载以前的数据
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [self loadMoreData];
    }];
    
    
}



#pragma mark - Table view data source


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.array.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    WJEssAndNewBaseCell *cell = [tableView dequeueReusableCellWithIdentifier:UPCell forIndexPath:indexPath];
    cell.model = self.array[indexPath.row];
    
    [cell.upButton addTarget:self action:@selector(upButtonAction:) forControlEvents:1<<6];
    [cell.belowButton addTarget:self action:@selector(belowButtonAction:) forControlEvents:1<<6];
    
    cell.videoView.middenImage.tag = 3000 + indexPath.row;
    
    cell.audioView.progressView.tag = 4000 + indexPath.row;
    
    if (cell.videoView.middenImage.tag != self.presentTag) {
        cell.videoView.playView.hidden = YES;
    }
    
    if (cell.audioView.progressView.tag != self.presentTag) {
        cell.audioView.progressView.hidden = YES;
        cell.audioView.textProgressView.hidden = YES;
        [cell.audioView.player pause];
    }
    
    
    cell.upButton.tag = indexPath.row + 1000;
    cell.belowButton.tag = indexPath.row + 2000;
    
    self.isClick = YES;
    
    self.isHas = NO;
    
    self.isBelowHas = NO;
    
    //////////只需要判断有没有看就可以了
    
    for (NSNumber *number in self.clickUpButton) {
        if (cell.upButton.tag == number.integerValue ) {
            self.isHas = YES;  break;
        }
    }
    
    if (self.isHas) {
        [cell.upButton setImage:[UIImage imageNamed:@"mainCellDingClick"] forState:0];
        [cell.upButton setTitle:[NSString stringWithFormat:@"%ld",(long)(cell.model.Meup.integerValue + 1)] forState:0];
        [cell.upButton setTitleColor:[UIColor redColor] forState:0];
        
        cell.belowButton.enabled = NO;
        
    }else{
        
        [cell.upButton setImage:[UIImage imageNamed:@"mainCellDing"] forState:UIControlStateNormal];
        [cell.upButton setTitle:cell.model.Meup forState:UIControlStateNormal];
        [cell.upButton setTitleColor:[UIColor grayColor] forState:0];
        
    }
    
    
    for (NSNumber *number in self.clickBelowButton) {
        if (cell.belowButton.tag == number.integerValue) {
            self.isBelowHas = YES; break;
        }
    }
    
    if (self.isBelowHas) {
        
        [cell.belowButton setImage:[UIImage imageNamed:@"mainCellCaiClick"] forState:0];
        [cell.belowButton setTitle:[NSString stringWithFormat:@"%ld",(long)cell.model.Medown.integerValue + 1] forState:0];
        [cell.belowButton setTitleColor:[UIColor redColor] forState:0];
        
        cell.upButton.enabled = NO;
        
    }else{
        [cell.belowButton setImage:[UIImage imageNamed:@"mainCellCai@2x副本"] forState:UIControlStateNormal];
        [cell.belowButton setTitle:cell.model.Medown forState:0];
        [cell.belowButton setTitleColor:[UIColor grayColor] forState:0];
        
    }
    
#pragma mark - 点击进入我的评论
    __block typeof(self) weakSelf = self;
    cell.clickComment = ^(WJEssAndNewModel *model){
        
        NSLog(@"点击了评论");
        
        WJEssAndNewPLVC *vc = [[WJEssAndNewPLVC alloc]init];
        
        vc.model = model;
                
        [weakSelf.navigationController pushViewController:vc animated:YES];
        
        [vc release];
    };
    
    cell.clickHeader = ^(NSString *name,NSString *uID){
        
        NSLog(@"点击了头像");
        
        WJLastViewController *vc = [[WJLastViewController alloc]init];
        
        vc.userID = uID;
        
        vc.userName = name;
        
        [weakSelf.navigationController pushViewController:vc animated:YES];
        
        [vc release];
        
    };
    
    cell.tagsVC.tagBlock = ^(NSInteger ID,NSString *name){
        
        WJ_TJDY_VC *vc = [[WJ_TJDY_VC alloc]init];
        
        vc.theme_id = ID;
        
        vc.title = name;
        
        [weakSelf.navigationController pushViewController:vc animated:YES];
        [vc release];
    };
    
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    WJEssAndNewModel *model = self.array[indexPath.row];
    return model.cellHeight;
}


- (void)upButtonAction:(WJEssAndNewButton *)button
{
    WJEssAndNewModel *model = self.array[button.tag - 1000];
    if  (self.isClick ) {
        
        [button setImage:[UIImage imageNamed:@"mainCellDingClick"] forState:0];
        [button setTitle:[NSString stringWithFormat:@"%ld",(long)(model.Meup.integerValue + 1)] forState:0];
        [button setTitleColor:[UIColor redColor] forState:0];
        
        self.isClick = !self.isClick;
        
        NSNumber *number = [NSNumber numberWithInteger:button.tag];
        
        [self.clickUpButton addObject:number];
    }
   
    
}
- (void)belowButtonAction:(WJEssAndNewButton *)button
{
    WJEssAndNewModel *model = self.array[button.tag - 2000];
    
     if (self.isClick ) {
         
    [button setImage:[UIImage imageNamed:@"mainCellCaiClick"] forState:0];
    [button setTitle:[NSString stringWithFormat:@"%ld",(long)(model.Medown.integerValue + 1)] forState:0];
    [button setTitleColor:[UIColor redColor] forState:0];
    self.isClick = !self.isClick;
    NSNumber *number = [NSNumber numberWithInteger:button.tag];
    [self.clickBelowButton  addObject:number];
      
     }
    
}




- (void)loadNewData
{
    
    
    NSString *str1 = [self.url stringByReplacingOccurrencesOfString:@"http://" withString:@""];
    NSString *str2 = [str1 stringByReplacingOccurrencesOfString:@".budejie.com/topic/" withString:@""];
    NSString *str3 = [str2 stringByReplacingOccurrencesOfString:@"/bs0315-iphone-4.2/0-20.json" withString:@""];
    NSString *str4 = [str3 stringByReplacingOccurrencesOfString:@"/" withString:@""];
    NSString *str5 = [NSString stringWithFormat:@"%@.plist",str4];
    
    NSString *str = [KESHAN stringByAppendingPathComponent:str5];
    NSLog(@"%@",str);
    
    [WJNetTool GET:self.url body:nil header:nil response:WJJSON success:^(id resuposeObject) {
        
        // 写入文件
        BOOL result = [resuposeObject writeToFile:str atomically:YES];
        if (result) {
            NSLog(@"分类页写入数据成功");
        }
        else {
            NSLog(@"分类页写入数据失败");
        }
        
        NSDictionary *dic = resuposeObject;
        
        NSArray *array = dic[@"list"];
        
        if (dic[@"info"][@"np"] != nil) {
            self.np = dic[@"info"][@"np"];
        }
        
        [self.array removeAllObjects];
        
        for (NSDictionary *dic in array) {
            WJEssAndNewModel *model = [[WJEssAndNewModel alloc]initWithDic:dic];
            [self.array addObject:model];
            [model release];
        }
        
        [self.tableView reloadData];
        // 结束刷新
        [self.tableView.mj_header endRefreshing];
        self.progress.hidden = YES;
        
    } failure:^(NSError *error) {
        //显示加载失败的信息
        [SVProgressHUD showErrorWithStatus:@"链接失败,读取本地数据"];
        // 列表大字典
        NSDictionary *dic = [NSDictionary dictionaryWithContentsOfFile:str];
        NSArray *array = dic[@"list"];
        
        self.np = dic[@"info"][@"np"];
        
        [self.array removeAllObjects];
        
        for (NSDictionary *dic in array) {
            WJEssAndNewModel *model = [[WJEssAndNewModel alloc]initWithDic:dic];
            [self.array addObject:model];
            [model release];
        }
        
        [self.tableView reloadData];
        // 结束刷新
        [self.tableView.mj_header endRefreshing];
        self.progress.hidden = YES;
    }];

    
    
    
}




- (void)loadMoreData
{
    [self.tableView.mj_header endRefreshing];
//    NSLog(@"%@",self.np);
    
    if ([self.np isKindOfClass:[NSNull class]] || self.np == nil)
    {
        [self.tableView.mj_footer endRefreshingWithNoMoreData];
        return;
    }
    
//    NSRange range = [_url rangeOfString:@"4.2/"];
//    NSString *preUrl = [_url substringToIndex:range.location + 4];
//    NSString *lastUrl = @"-20.json";
    //    NSString *url = [NSString stringWithFormat:@"%@%@%@",preUrl,self.np,lastUrl];
    
    NSString *oldStr = [NSString stringWithFormat:@"%@-20.json",self.np];
    NSString *str4 = [self.url stringByReplacingOccurrencesOfString:@"0-20.json" withString:oldStr];
    
    
    [WJNetTool GET:str4 body:nil header:nil response:WJJSON success:^(id resuposeObject) {
 
#pragma mark - 如果self.np 为空的话根本请求不到数据
        if(![resuposeObject isKindOfClass:[NSDictionary class]])
        {
            self.tableView.mj_header.hidden = YES;
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
            return;
        }
        
        NSDictionary *dic = resuposeObject;
        
        NSArray *array = dic[@"list"];
        
        self.np = dic[@"info"][@"np"];
        
        
        for (NSDictionary *dic in array) {
            WJEssAndNewModel *model = [[WJEssAndNewModel alloc]initWithDic:dic];
            [self.array addObject:model];
            [model release];
        }
        
        [self.tableView reloadData];
        self.progress.hidden = YES;
        
        [self.tableView.mj_footer endRefreshing];
        
        
        
    } failure:^(NSError *error) {
        //显示加载失败的信息
        [SVProgressHUD showErrorWithStatus:@"加载失败"];
        self.progress.hidden = YES;

    }];
    
    
    
}




























- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}




@end
